package com.rainng.coursesystem.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rainng.coursesystem.dao.mapper.AnswerMapper;
import com.rainng.coursesystem.dao.mapper.CourseMapper;
import com.rainng.coursesystem.dao.mapper.HomeWorkMapper;
import com.rainng.coursesystem.dao.mapper.StudentCourseMapper;
import com.rainng.coursesystem.model.bo.AnswerDTO;
import com.rainng.coursesystem.model.entity.AnswerEntity;
import com.rainng.coursesystem.model.entity.CourseEntity;
import com.rainng.coursesystem.model.entity.HomeworkEntity;
import com.rainng.coursesystem.model.bo.HomeWorkDTO;
import com.rainng.coursesystem.model.vo.response.ResultVO;
import com.rainng.coursesystem.model.vo.response.table.StudentAnswerVO;
import com.rainng.coursesystem.model.vo.response.table.StudentHomeworkVO;
import com.rainng.coursesystem.model.vo.response.table.TeacherHomeworkVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class HomeWorkService extends BaseService {

    @Value("${yun.alioss.access-key-id}")
    private  String accessKeyId;
    @Value("${yun.alioss.access-key-secret}")
    private String accessKeySecret;
    @Value("${yun.alioss.endpoint}")
    private String endpoint;
    @Value("${yun.alioss.bucket-name}")
    private String bucketName;


    @Autowired
    private HomeWorkMapper mapper;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private AnswerMapper answerMapper;
    @Autowired
    private StudentCourseMapper studentCourseMapper;

    public ResultVO addHomeWork(HomeWorkDTO dto) {

        HomeworkEntity entity = new HomeworkEntity();
        BeanUtils.copyProperties(dto,entity);
        LocalDateTime now = LocalDateTime.now();
        entity.setCreateTime(now);
        String filePath = fileUpLoad(dto.getFile());

        entity.setPath(filePath);
        mapper.insert(entity);
        return result("success");

    }

    public ResultVO teacherGetHomeWorkList() {

        Integer teacherId = getUserId();
        List<CourseEntity> courseList = courseMapper.selectList(new QueryWrapper<CourseEntity>().eq("course_teacher_id", teacherId));
        List<Integer> courseIds = courseList.stream().map(c -> c.getId()).collect(Collectors.toList());

        //查询该教师管理的课程下的所有作业
        List<HomeworkEntity> list = mapper.selectList(new QueryWrapper<HomeworkEntity>().in("course_id",courseIds));

        List<TeacherHomeworkVO> list1=new ArrayList<>();
        for (HomeworkEntity homeworkEntity : list) {
            TeacherHomeworkVO teacherHomeworkVO = new TeacherHomeworkVO();
            BeanUtils.copyProperties(homeworkEntity,teacherHomeworkVO);
            //设置课程名
            teacherHomeworkVO.setCourseName(courseMapper.selectById(homeworkEntity.getCourseId()).getName());
            //设置提交人数
            teacherHomeworkVO.setSubmitCount(answerMapper.getCountByHomeworkId(homeworkEntity.getId()));
            list1.add(teacherHomeworkVO);
        }
        return result(list1);
    }
    @Transactional
    public ResultVO getYesHomeWorkList() {
        List<AnswerEntity> answerEntities = answerMapper.getByStudentId(getUserId());
        List<StudentAnswerVO> studentAnswerVOS=new ArrayList<>();
        for (AnswerEntity answerEntity : answerEntities) {
            StudentAnswerVO studentAnswerVO = new StudentAnswerVO();
            studentAnswerVO.setCourseName(courseMapper.selectById(mapper.selectById(answerEntity.getHomeworkId()).getCourseId()).getName());
            studentAnswerVO.setTitle(mapper.selectById(answerEntity.getHomeworkId()).getTitle());
            studentAnswerVO.setId(answerEntity.getId());
            studentAnswerVO.setGrade(answerEntity.getGrade());
            studentAnswerVO.setCreateTime(answerEntity.getCreateTime());
            studentAnswerVOS.add(studentAnswerVO);
        }
        return result(studentAnswerVOS);
    }
    public ResultVO getNoHomeWorkList() {
        List<Integer> courseList = studentCourseMapper.getCourseListByStudentId(getUserId());
        List<Integer> homeworkIdList = answerMapper.getHomeworkIdListByStudentId(getUserId());
        List<HomeworkEntity> list = mapper.selectByCourseListAndHomeworkIdList1(courseList,homeworkIdList);
        List<StudentHomeworkVO> list1=new ArrayList<>();
        for (HomeworkEntity homeworkEntity : list) {
            StudentHomeworkVO studentHomeworkVO = new StudentHomeworkVO();
            BeanUtils.copyProperties(homeworkEntity,studentHomeworkVO);
            //设置课程名
            studentHomeworkVO.setCourseName(courseMapper.selectById(homeworkEntity.getCourseId()).getName());
            list1.add(studentHomeworkVO);
        }
        return result(list1);
    }




    private String fileUpLoad(MultipartFile file) {

        if (file == null || file.isEmpty()) {
            return null;
        }

        try {
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            // 截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 构造新文件名称
            String objectName = UUID.randomUUID() + extension;
            // 文件的请求路径
            String filePath = upload(file.getBytes(), objectName);

            return filePath;
        } catch (IOException e) {

        }
        return null;

    }

    private String upload(byte[] bytes, String objectName) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (com.aliyun.oss.ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        // todo 自定义文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);

        return stringBuilder.toString();
    }

    public ResultVO getAnswerById(Integer id) {
        AnswerEntity answerEntity = answerMapper.getById(id);
        return result(answerEntity);
    }

    public ResultVO submit(AnswerDTO answerDTO) throws IOException {
        MultipartFile file = answerDTO.getPath();
        if (file.isEmpty()) {
            return null;
        }

        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 截取原始文件名的后缀
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 构造新文件名称
        String objectName = UUID.randomUUID() + extension;
        // 文件的请求路径
        String filePath = upload(file.getBytes(), objectName);

        AnswerEntity answerEntity = new AnswerEntity();
        answerEntity.setStudentId(getUserId());
        answerEntity.setCreateTime(LocalDateTime.now());
        answerEntity.setPath(filePath);
        answerEntity.setHomeworkId(answerDTO.getHomeworkId());
        answerEntity.setDescription(answerDTO.getDescription());
        answerMapper.insert(answerEntity);
        return result("提交成功");
    }


    public ResultVO updateHomework(Integer homeworkId, HomeWorkDTO dto) {
        HomeworkEntity entity = new HomeworkEntity();
        BeanUtils.copyProperties(dto,entity);
        entity.setId(homeworkId);
        mapper.updateById(entity);
        return result("success");
    }

    public ResultVO deleteHomework(Integer homeworkId) {

        mapper.deleteById(homeworkId);
        QueryWrapper<AnswerEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("homework_id",homeworkId);
        answerMapper.delete(queryWrapper);
        return result("success");
    }

    public ResultVO gradeHomework(Integer homeworkId, Integer studentId, String grade) {


        QueryWrapper<AnswerEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("homework_id",homeworkId);
        queryWrapper.eq("student_id",studentId);
        AnswerEntity answerEntity = answerMapper.selectOne(queryWrapper);
        answerEntity.setGrade(grade);

        answerMapper.updateById(answerEntity);

        return result("success");

    }
}
